namespace egret.socketio.engine {

    export class WebSocket extends Transport {
        public static NAME: string = 'websocket';

        private ws: egret.WebSocket;

        constructor(opts: TransportUri) {
            super(opts);
            this.name = WebSocket.NAME;
        }

        private addEventListeners(): void {
            //添加收到数据侦听，收到数据会调用此方法
            this.ws.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onWsData, this);
            //添加链接打开侦听，连接成功会调用此方法
            this.ws.addEventListener(egret.Event.CONNECT, this.onWsOpen, this);
            //添加链接关闭侦听，手动关闭或者服务器关闭连接会调用此方法
            this.ws.addEventListener(egret.Event.CLOSE, this.onWsClose, this);
            //添加异常侦听，出现异常会调用此方法
            this.ws.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onWsError, this);
        }

        protected write(packets: Packet[]): void {
            this.writable = false;

            let total = packets.length;

            let done = () => {
                new Promise((resolve, reject) => {
                    this.ws.flush();
                    this.emit(_emEvent.EVENT_FLUSH);
                    resolve(1);
                }).then(() => {
                    this.writable = true;
                    this.emit(_emEvent.EVENT_DRAIN);
                });
            };

            for (let i = 0; i < total; i++) {
                if (this.readyState !== _emReadyState.OPENING && this.readyState !== _emReadyState.OPEN) {
                    break;
                }

                Parser.encodePacket(packets[i], false, (message: string) => {

                    this.ws.writeUTF(message);

                    --total || done();
                });
            }


        }

        protected onWsOpen(evt: egret.Event): void {
            console.debug("onWsOpen");
            super.onOpen();
        }

        protected onWsData(evt: egret.ProgressEvent): void {

            let msg = this.ws.readUTF();
            super.onData(msg);
        }

        protected onWsError(evt: IOErrorEvent) {
            super.onError(evt.data);
        }

        protected onWsClose(): void {
            super.onClose();
        }

        protected doOpen(): void {
            let uri = this.uri();

            this.ws = new egret.WebSocket();
            this.ws.type = egret.WebSocket.TYPE_STRING; //暂时只支持文本模式 
            this.addEventListeners();
            this.ws.connectByUrl(uri);
        }

        protected doClose(): void {
            if (typeof this.ws !== 'undefined') {
                this.ws.close();
                this.ws = null;
            }
        }

        protected uri(): string {
            let uri = this.opts.clone();
            uri.addTrailingSlash();
            uri.replaceQueryParam('b64', 1);
            let schema = uri.secure ? 'wss' : 'ws';
            uri.protocol = schema;

            if (uri.timestampRequests) {
                uri.addQueryParam(uri.timestampParam, Yeast.yeast());
            }
            return uri.toString();
        }
    }

}